package com.cz.nongyetongv5.activity;

import java.net.URLEncoder;
import java.util.Calendar;
import java.util.GregorianCalendar;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.cz.nongyetongv5.R;
import com.cz.nongyetongv5.activity.ChouyangrenwuActivity.MobInterp;
import com.cz.nongyetongv5.application.InitApplication;
import com.cz.nongyetongv5.bean.User;
import com.cz.nongyetongv5.custom.BlueLoadingProgress;
import com.cz.nongyetongv5.utils.Conf;
import com.cz.nongyetongv5.utils.ConfigUtil;
import com.cz.nongyetongv5.utils.GoHomeUtil;

public class ChanPinJianCeStatisticsActivity extends Activity implements
        OnClickListener {

    private WebView wvStart;

    private Button btnLeft;

    private Button btnMiddle;

    private Button btnRight;

    private User user;

    private ViewGroup btnBack;

    private BlueLoadingProgress blpLoading = null;

    private TextView titleState = null;

    @Override
    protected void onDestroy() {

        InitApplication initApplication = (InitApplication) getApplicationContext();

        initApplication.getActivities().remove(this);

        // TODO Auto-generated method stub
        super.onDestroy();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        InitApplication initApplication = (InitApplication) getApplicationContext();

        initApplication.getActivities().add(this);

        setContentView(R.layout.chanpinjiance_start);


        titleState = (TextView) findViewById(R.id.titleState);

        wvStart = (WebView) findViewById(R.id.wvStart);

        btnLeft = (Button) findViewById(R.id.btnLeft);

        btnLeft.setBackgroundColor(getResources().getColor(R.color.title_color));

        btnLeft.setOnClickListener(this);

        btnMiddle = (Button) findViewById(R.id.btnMiddle);

        btnMiddle.setOnClickListener(this);

        btnRight = (Button) findViewById(R.id.btnRight);

        btnRight.setOnClickListener(this);

        btnBack = (ViewGroup) findViewById(R.id.btnBack);
        btnBack.setOnClickListener(this);

        blpLoading = (BlueLoadingProgress) findViewById(R.id.blpLoading);
        blpLoading.setVisibility(View.GONE);

        user = (User) getIntent().getSerializableExtra("user");

        // 存在网络的情况下

        // 启动javascr
        wvStart.getSettings().setJavaScriptEnabled(true);

        wvStart.getSettings().setLoadsImagesAutomatically(true);
        wvStart.addJavascriptInterface(new MobInterp(), "mobinterp");
        wvStart.setWebViewClient(new WebViewClient() {

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {

                blpLoading.setVisibility(View.VISIBLE);

                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {

                if (blpLoading != null) {
                    blpLoading.stopLoading();
                    blpLoading.setVisibility(View.GONE);
                }
                super.onPageFinished(view, url);
            }

        });
        //

        // String url = CommonConstants.URLSUFFER
        // + getString(R.string.chanpinjiance_count_url)
        // + user.getKnowRegion();
        //
        //		String url = new ConfigUtil(getResources()).getPreHttpUrl()
        //				+ getString(R.string.chanpinjiance_count_url)
        //				+ user.getKnowRegion();
        wvStart.loadUrl(getStatUrl());

        loadRightTitle();

    }

    private String year = String.valueOf(Calendar.getInstance().get(Calendar.YEAR));
    private String nature = "1";

    private String getUrl(String data) {
        try {
            return URLEncoder.encode(URLEncoder.encode(data, "utf-8"), "utf-8");

            // return new String(Base64.encode(user.getUsername().getBytes("utf-8"),Base64.DEFAULT));
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return user.getUsername();
    }

    private String getStatUrl() {


        String param = "{\"user\":\"" + user.getUsername() + "\",\"year\":\"" + year + "\",\"nature\":" + nature + "}";
        String aa = Conf.v160918_pretask + "GetDetectList.html?year=" + year + "&param=" + getUrl(param);
        Log.d("test_url", aa);
        return aa;
    }

    /**
     * 加载去主页的按钮
     */
    public void loadRightTitle() {

        ViewGroup btnMeanMore = (ViewGroup) findViewById(R.id.btnMeanMore);

        View view = GoHomeUtil.createPopView(getApplicationContext(),
                new String[]{"主页", "去年", "今年"});

        // 弹出更多的菜单
        final PopupWindow pop = new PopupWindow(view,
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, false);

        // 需要设置一下此参数，点击外边可消失
        pop.setBackgroundDrawable(new BitmapDrawable());

        // 设置点击窗口外边窗口消失
        pop.setOutsideTouchable(true);

        // 设置此参数获得焦点，否则无法点击
        pop.setFocusable(true);

        final Button btn01 = (Button) pop.getContentView().findViewWithTag(
                "btn0");

        final Button btn02 = (Button) pop.getContentView().findViewWithTag(
                "btn1");

        final Button btn03 = (Button) pop.getContentView().findViewWithTag(
                "btn2");

        OnClickListener menuOnClick = new OnClickListener() {

            @Override
            public void onClick(View v) {

                if (v == btn01) {
                    GoHomeUtil.goHome(getApplicationContext());
                }
                if (v == btn02) {
                    //					titleState.setText("当前数据:去年");

                    GregorianCalendar calendar = new GregorianCalendar();
                    calendar.add(Calendar.YEAR, -1);

                    String year1 = calendar.get(Calendar.YEAR) + "";
                    //
                    //					//					String url = new ConfigUtil(getResources()).getPreHttpUrl()
                    //					//							+ getString(R.string.chanpinjiance_count_url)
                    //					//							+ user.getKnowRegion() + "/year/" + year;
                    year = year1;
                    wvStart.loadUrl(getStatUrl());
                    titleState.setText("当前数据:去年");
                }

                if (v == btn03) {
                    String url = new ConfigUtil(getResources()).getPreHttpUrl()
                            + getString(R.string.chanpinjiance_count_url)
                            + user.getKnowRegion();

                    year = String.valueOf(Calendar.getInstance().get(Calendar.YEAR));
                    wvStart.loadUrl(getStatUrl());

                    titleState.setText("当前数据:今年");
                }

                pop.dismiss();
            }
        };

        btn01.setOnClickListener(menuOnClick);
        btn02.setOnClickListener(menuOnClick);
        btn03.setOnClickListener(menuOnClick);

        btnMeanMore = (ViewGroup) findViewById(R.id.btnMeanMore);


        btnMeanMore.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                if (pop.isShowing()) {
                    // 隐藏窗口，如果设置了点击窗口外小时即不需要此方式隐藏
                    pop.dismiss();
                } else {
                    // 显示窗口
                    pop.showAsDropDown(v);
                }

            }
        });

    }

    @Override
    public void onClick(View v) {

        if (v == btnBack) {

            finish();

            return;
        }

        btnLeft.setBackgroundResource(R.drawable.btn_back_pressed);
        btnRight.setBackgroundResource(R.drawable.btn_back_pressed);
        btnMiddle.setBackgroundResource(R.drawable.btn_back_pressed);
        if (v == btnLeft) {

            btnLeft.setBackgroundColor(getResources().getColor(
                    R.color.title_color));
            nature = "1";
            wvStart.loadUrl(getStatUrl());

        } else if (v == btnMiddle) {


            //			String requestUrl = getString(R.string.chanpinjiance_history_url);
            //
            //			requestUrl = new ConfigUtil(getResources()).getPreHttpUrl()
            //					+ requestUrl + user.getKnowRegion();
            //
            //			intent.putExtra("url", requestUrl);
            //
            //			// 传递到下一个页面
            //			intent.putExtra("title", "产品检测记录列表");
            //
            //			intent.putExtra("more", true);
            //
            //			startActivity(intent);


            btnMiddle.setBackgroundColor(getResources().getColor(
                    R.color.title_color));
            nature = "2";
            wvStart.loadUrl(getStatUrl());

        } else if (btnRight == v) {


            //			Intent intent = new Intent(this, ChanPinJianCeActivity.class);
            //
            //			// 传递到下一个页面
            //			intent.putExtra("user", this.user);
            //
            //			startActivity(intent);

            btnLeft.setBackgroundColor(getResources().getColor(
                    R.color.title_color));
            btnRight.setBackgroundResource(R.drawable.btn_back_pressed);
            btnRight.setBackgroundColor(getResources().getColor(
                    R.color.title_color));
            nature = "2";
            wvStart.loadUrl(getStatUrl());
        }

    }

    public class MobInterp {

        public MobInterp() {

        }

        @JavascriptInterface
        public void toDetectDetail(String pid) {
            Intent intent = new Intent(ChanPinJianCeStatisticsActivity.this, WebDetailActivity.class);
            intent.putExtra("pid", pid);
            intent.putExtra("type", "detectDetail");
            intent.putExtra("title", "检测详情");
            intent.putExtra("n", nature);
            intent.putExtra("user", user);
            startActivity(intent);
        }


    }

}
